<?php
class admin extends base{
  function __construct(){
    global $site;
    parent::__construct();
    if(!$this->u['uuid']){
      redirect('/?/login/?&rtu=/?/admin/',"请先登录");
    }
    if($this->u['level'] < 10 ) redirect(BASE,'权限不够');
    $this->m = load('m/node_m');
    $sid = $_COOKIE['sid'];
    if(!$sid && seg(2)!='site'){
      redirect('/?/admin/site',$param);
    }
    // 获取当前空间数据
    $site = load('m/site_m')->get_one($sid);
    //print_r($site);
    define('SID',$sid);
  }

  function index()
  {
    redirect("/?/admin/page/");
  }

  function site($action = '')
  {
    switch($action){
      case 'edit':
        $this->site_edit(seg(4));
        break;
      default:
        $this->site_list($action);
    }
  }

  function site_list($uuid = 0)
  {
    if($uuid){
      setcookie('sid',$uuid);
      redirect('?/admin/',$param);
    }
    $param['sites'] = load('m/site_m')->get();
    $this->display('v/admin/site_list',$param);
  }

  function site_edit($uuid = 0)
  {
    if($_POST['name']){
      if($uuid){
        load('m/site_m')->update($uuid,$_POST);
      }
      else {
        $_POST['uuid'] = uniqid();
        load('m/site_m')->add($_POST);
      }
      redirect("?/admin/site");
    }
    if($uuid){
      $param['site'] = load('m/site_m')->get_one($uuid);
      $param['templates'] = load('m/node_m')->get( " and sid='$uuid' and  type='template'");
    }
    $this->display("v/admin/site_add",$param);
  }

  /* upload 方法同事支持 tinymce 和系统本身文件上传 */
  function upload( $file = null )
  {
    global $site;
    if($file == null)
    {
      $ajax = true;
      $file = $_FILES['file'];
    }
    if(empty($file))return;
    //文件保存目录URL
    $save_url = '/files/'.$site['uuid'].'/';
    //定义允许上传的文件扩展名
    $ext_arr = array(
      'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
      'flash' => array('swf', 'flv'),
      'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
      'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
    );
    //最大文件大小
    $max_size = 1000000;
    $save_path ='files/'.$site['uuid'].'/';
    if(!is_dir($save_path)){
      mkdir($save_path,0777,true);
    }

    //PHP上传失败
    if (!empty($file['error'])) {
      switch($file['error']){
        case '1':
          $error = '超过php.ini允许的大小。';
          break;
        case '2':
          $error = '超过表单允许的大小。';
          break;
        case '3':
          $error = '图片只有部分被上传。';
          break;
        case '4':
          $error = '请选择图片。';
          break;
        case '6':
          $error = '找不到临时目录。';
          break;
        case '7':
          $error = '写文件到硬盘出错。';
          break;
        case '8':
          $error = 'File upload stopped by extension。';
          break;
        case '999':
        default:
          $error = '未知错误。';
      }
    }

    //原文件名
    $file_name = $file['name'];
    //服务器上临时文件名
    $tmp_name = $file['tmp_name'];
    //文件大小
    $file_size = $file['size'];
    //检查文件名
    if (!$file_name) {
      $error = ("请选择文件。");
    }
    //检查目录
    if (@is_dir($save_path) === false) {
      $error =  "上传目录不存在。";
    }
    //检查目录写权限
    if (@is_writable($save_path) === false) {
      $error = "上传目录没有写权限。";
    }
    //检查是否已上传
    if (@is_uploaded_file($tmp_name) === false) {
      $error =  "上传失败。";
    }
    //检查文件大小
    if ($file_size > $max_size) {
      $error = "上传文件大小超过限制。";
    }

    $temp_arr = explode(".", $file_name);
    $file_ext = array_pop($temp_arr);
    $file_ext = trim($file_ext);
    $file_ext = strtolower($file_ext);
    //检查扩展名
    if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
      $error = "上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。";
    }
    $ymd = date("Ymd");
    $save_path .= $ymd . "/";
    $save_url .= $ymd . "/";
    if (!file_exists($save_path)) {
      mkdir($save_path);
    }
    //新文件名
    $new_file_name = date("YmdHis") . '_' . rand(100, 999) . '.' . $file_ext;
    //移动文件
    $file_path = $save_path . $new_file_name;
    if (move_uploaded_file($tmp_name, $file_path) === false) {
      $error = "上传文件失败。";
    }
    @chmod($file_path, 0644);
    $file_url = $save_url . $new_file_name;

    if($ajax){
      header('Content-type: text/html; charset=UTF-8');
      if($error )
      {
        header("HTTP/1.1 400 ERROR: $msg");
      }
      else{
        echo json_encode(array('location' => $file_url));
      }
      exit;
    }
    else{
      return $file_url;
    }
  }

  function json_alert($msg) {
    die($msg);
    //header('Content-type: text/html; charset=UTF-8');
    exit;
    // header('Content-type: text/html; charset=UTF-8');
    // echo json_encode(array('error' => 1, 'message' => $msg));
    // exit;
  }

  function page($upid = '0' ,$id = 0,$model_id = 0)
  {
    switch($upid){
      case 'edit':
        $this->page_edit($id);
        break;
      case 'add':
        //$this->add($id,$model_id);
        $this->page_edit( 0 , $id );
        break;
      case 'del':
        $this->del($id);
        break;
      default:
        $this->page_list($upid);
    }
  }

  function page_list( $upid = 0 )
  {
    if(isset($_POST['order_by'])){
      foreach($_POST['order_by'] as $k => $v){
        $this->m->update($k, array('order_by'=> $v ));
      }
    }
    $param['uper'] = array();
    $param['upid'] = $upid;

    //上级页面id
    if(!empty($upid)&&$upid!=0){
      $uper_id = $this->m->get_one($upid);
      $param['uper'][$param['upid']] = $uper_id['title'];
      while ($uper_id['upid']!=0) {
        $a = $uper_id['upid'];
        $uper_id = $this->m->get_one($uper_id['upid']);
        $param['uper'][$a] = $uper_id['title'];
      }
      $param['uper'] = array_reverse($param['uper'],true);
    }

    $tot = $this->m->count( " and `type` = 'page' and upid = '$upid' " );
    $psize = 30;
    $pcurrent = isset( $_GET['p'] )? $_GET['p']:0;
    $param['pagination'] = pagination($tot , $pcurrent , $psize ,'/admin/page/index/'.$rel_id.'/?p=');
    $param['records'] = array();
    $a = load('m/node_m')->get( " and `type` = 'page' and sid='".SID."' and upid = '$upid' order by `order`,`uuid` asc" , $pcurrent ,  $psize);
    foreach ($a as $k => $v) {
      // print_r($v);
      $v['meta'] = _decode($v['meta']);
      array_push($param['records'], $v);
    }
    $this->display('v/admin/index',$param);
  }

  function order_edit($id, $type = '')
  {
    $pnode = $this->m->get($id);
    if($type == 'down') {
      $qnode = $this->m->db->query("select uuid,`order` from node where `order`>$pnode[order] and `type` = 'page' and upid=$pnode[upid] order by `order` asc limit 1");
      $this->m->update($id, array('order' => $qnode[0]['order']));
      $this->m->update($qnode[0]['uuid'], array('order' => $pnode['order']));
    } else if($type == 'up') {
      $qnode = $this->m->db->query("select uuid,`order` from node where `order`<$pnode[order] and `type` = 'page' and upid=$pnode[upid] order by `order` desc limit 1");
      $this->m->update($id, array('order' => $qnode[0]['order']));
      $this->m->update($qnode[0]['uuid'], array('order' => $pnode['order']));
    }
  }

  function page_edit($uuid = 0,  $upid = 0){
    if($_POST){
      if(!$uuid){
        //添加数据
        $_POST['uuid'] =uniqid();
        $_POST['upid'] = $upid;
      }
      else{
        $_POST['uuid'] =$uuid;
      }
      $_POST['sid'] = SID;
      // 图片上传
      if(isset($_FILES)&&!empty($_FILES)){
        foreach ($_FILES['meta']['name'] as $key => $name){
          // 组装
          if($name){
            $file = array(
              'name' =>$name,
              'type'=> $_FILES['meta']['type'][$key],
              'tmp_name' => $_FILES['meta']['tmp_name'][$key],
              'error'=> $_FILES['meta']['error'][$key],
              'size'=> $_FILES['meta']['size'][$key]
            );
            $_POST['meta'][$key] = $this->upload($file);
          }
          else{
            $_POST['meta'][$key] = $_POST['meta'][$key.'_old'];
          }
          //$a =  $this->upload($val);
        }
      }

      //    print_r($_FILES);

      $_POST['meta'] = _encode($_POST['meta']);
      $_POST['exts'] = _encode($_POST['exts']);
      $_POST['update_date'] = time();
      $this->m->replace($_POST);
      if(!$_POST['submit_type'])redirect('?/admin/page/'.$_POST['upid'],'提交成功');
      if(!$uuid){
        header('location:?/admin/page/edit/'.$_POST['uuid'],'',0);
      }
    }

    $page = $this->m->get_one($uuid);
    $page['meta'] = _decode($page['meta']);

    $config  = $this->m->db->query("select * from node where `type` in  ('model','layout' ) and sid = '".SID."' ");
    foreach($config as $item){
      $cid = $item['uuid'];
      $cname = $item['name'];
      $ctype = $item['type'];
      $param[$ctype][$cid] = $cname;
      if($page['meta']['model'] == $cid) $param['model_cfg'] = _decode($item['content']);
    }

    if($upid){
      // 获取上级页面对本页面的额定义 (模型\排版)
      $uppage = $this->m->get_one($upid);
      $uppage_meta = _decode($uppage['meta']);
      $page['meta']['model'] = $uppage_meta['son_model'];
      $page['meta']['layout'] = $uppage_meta['son_layout'];
    }

    $param['page'] = $page;
    $this->display('v/admin/page',$param);
  }

  function del($id)
  {
    $this->m->del($id);
    echo '1';
    exit;
  }

  function get_layout_list()
  {
    $layouts = glob(APP.'v/layout/*.php');
    foreach($layouts as $r){
      $ret[] = str_replace('.php','',basename($r));
    }
    return $ret;
  }

  function link($upid = 'list' ,$id = 0 )
  {
    switch($upid){
      case 'edit':
        $this->linkedit($id);
        break;
      case 'add':
        $this->linkadd($id);
        break;
      case 'del':
        $this->linkdel($id);
        break;
      default:
        $this->linklist($upid);
    }
  }

  function linklist($upid)
  {
    if(isset($_POST['order_by'])){
      foreach($_POST['order_by'] as $k => $v){
        $this->m->update($k, array('order_by'=> $v ));
      }
    }
    $param['rel_id'] = $rel_id;
    $tot = $this->m->count( " and `type` = 'link' " );
    $psize = 30;
    $pcurrent = isset( $_GET['p'] )? $_GET['p']:0;
    $param['pagination'] = pagination($tot , $pcurrent , $psize ,'/admin/link/index/'.$rel_id.'/?p=');
    $sid = SID;
    $param['records'] = load('m/node_m')->get( " and `type` = 'link' and `sid` = '$sid' " , $pcurrent ,  $psize);

    $this->display('v/admin/link',$param);
  }

  function linkadd()
  {
    if($_POST['name']){
      $_POST['update_date'] = $_POST['create_date'] = time();
      array_multisort(array_column($_POST['info'], 'order'), SORT_ASC, $_POST['info']);
      foreach($_POST['info'] as $info){
        if($info['title'])$ext[] = $info;
      }
      $_POST['ext'] = _encode($ext);
      $_POST['sid'] = SID;
      $_POST['uuid'] = uniqid();
      $this->m->add();
      redirect("?/admin/link/");
    }

    $this->display('v/admin/linkadd',$param);
  }

  function linkdel($id)
  {
    $this->m->del($id);
    echo '1';
    exit;
  }

  function linkedit( $id = 0)
  {
    if($_POST['name']){
      $_POST['update_date'] = time();
      array_multisort(array_column($_POST['info'], 'order'), SORT_ASC, $_POST['info']);
      foreach($_POST['info'] as $info){
        if($info['title'])$ext[] = $info;
      }
      $_POST['ext'] = _encode($ext);
      $_POST['sid'] = SID;
      //echo $_POST['ext'];
      $this->m->update($id);
      redirect("?/admin/link/");
    }

    $param['page'] = $page = $this->m->get_one($id);
    $param['ext'] = _decode($page['ext']);
    $this->display('v/admin/linkadd',$param);
  }

  function usr()
  {
    $records = glob(APP.'v/layout/*.php');
    foreach($records as $r){
      $nr['size'] = filesize($r);
      $nr['name'] = basename($r);
      $nr['time'] = filemtime($r);
     $nnr[] = $nr;
    }
    $this->display('v/admin/layout',array('records'=>$nnr));
  }

  function template( $upid = null , $id = 0 ){
    switch($upid){
      case 'edit':
        $this->template_edit($id);
        break;
      case 'add':
        $this->html_editor($id);
        break;
      case 'del':
        $this->del($id);
        break;
      default:
        $this->tlist();
    }
  }


  function layout( $upid = null , $id = 0 ){
    switch($upid){
      case 'edit':
        $this->template_edit($id,'layout');
        break;
      case 'add':
        $this->html_editor($id,'layout');
        break;
      case 'del':
        $this->del($id);
        break;
      default:
        $this->tlist($type='layout');
    }
  }

  function model( $upid = null , $id = 0 ){
    switch($upid){
      case 'edit':
        $this->template_edit($id,'model');
        break;
      case 'add':
        $this->html_editor($id,'model');
        break;
      case 'del':
        $this->del($id);
        break;
      default:
        $this->tlist($type='model');
    }
  }

  function tlist( $type="template" )
  {
    if(isset($_POST['order_by'])){
      foreach($_POST['order_by'] as $k => $v){
        $this->m->update($k, array('order_by'=> $v ));
      }
    }
    $param['upid'] = $upid;
    $param['uper'] = $this->m->get($upid);
    $param['type'] = $type;
    $psize = 300;
    $pcurrent = isset( $_GET['p'] )? $_GET['p']:0;
    $param['pagination'] = pagination($tot , $pcurrent , $psize ,'/admin/'.$type.'/index/'.$rel_id.'/?p=');
    $param['records'] = load('m/node_m')->get( " and sid='".SID."' and `type` = '".$type."' order by `order`,`uuid` asc" , $pcurrent ,  $psize);
    $this->display('v/admin/tlist',$param);
  }


  function html_editor( $upid = 0 ,$type = 'template')
  {
    load("lib/spyc");
    if($_POST['name']){
      $_POST['update_date'] = $_POST['create_date'] = time();
      $_POST['meta'] = _encode($_POST['meta']);
      if($_POST['type']=="model"){
        $_POST['content'] = yaml_parse($_POST['content']);
      }
      // var_dump($_POST);die;
      $_POST['uuid'] = uniqid();
      $id = $this->m->add();
      $layout_file = APP.'v/temp/'.$id.'.php';
      $content = htmlspecialchars_decode($_POST['content']);
      file_put_contents($layout_file, $content);
      redirect("?/admin/$type/$upid/");
    }
    $param['writable'] = is_writable(APP.'v/temp');
    $param['page']['upid'] = $upid;
    $param['page']['type'] = $type;
    $param['page']['sid'] = $_COOKIE['sid'];
    if($param['page']['type']=="model"){
      $param['page']['content'] = "
style:
  name: 类别
  type: text
abstract:
  name: 摘要
  type: rte
file:
  name: 文件
  type: file
logo:
  name: 图片
  type: file";
    }
    $this->display('v/admin/html_editor',$param);
  }



  function template_edit( $id = 0,$type = 'template')
  {
    load("lib/spyc");
    if($_POST['name']){
      $_POST['update_date'] = time();
      $_POST['meta'] = _encode($_POST['meta']);
      if($_POST['type']=="model"){
        $_POST['content'] = yaml_parse($_POST['content']);
      }else{
        $_POST['content'] = htmlspecialchars_decode($_POST['content']);
      }
      unset($_POST['type']);
      $this->m->update($id);
      $layout_file = APP.'v/template/'.$id.'.php';
      $content = htmlspecialchars_decode($_POST['content']);
      file_put_contents($layout_file, $content);
      redirect("?/admin/$type/");
    }
    $param['page'] = $page = $this->m->get_one( $id );
    if($page['type'] == "model"){
      $param['page']['content'] = _decode($param['page']['content']);
      $param['page']['content'] = yaml_emit($param['page']['content']);
    }
    // var_dump($param);die;
    $this->display('v/admin/html_editor',$param);
  }

  function user()
  {
    $user=$this->m->userlist();
    $param['user']=$user;
    $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '用户列表';
    $this->display('v/user/userlist',$param);
  }

  function userdelete(){
    $id=$_GET['uuid'];
    $this->m->userdelete($id);
    $user=$this->m->userlist();
    $param['user']=$user;
    $this->display('v/user/userlist',$param);
  }

  function profile(){
    $conf = array('email'=>'required|email','password'=>'required');
    $err = validate($conf);
    $param['user']=$user;
    if($_POST['password']!=$_POST['repassword']){
      $err['password']='两次密码不一样';
      $param['val'] = $_POST;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '更新';
      $this->display('v/user/update',$param);
    }elseif( $err === TRUE) {
      load('m/user_m')->userupdate($this->u['uuid'],$_POST);
       load('m/user_m')->logout();
      redirect(BASE,'修改成功，请登录。');
    }else {
      $usr_data = load('m/user_m')->get($this->u['uuid']);
      $param['val'] = $usr_data;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '更新';
      $this->display('v/user/update',$param);
    }
  }

  function redirect($info = '')
  {
    $info = urldecode($info);
    redirect($_SERVER['HTTP_REFERER'], $info);
  }

  function tag()
  {
    if($_POST['info']){
      foreach($_POST['info'] as $info){
        if($info['name'])$ext[] = $info;
      }
      $_POST['ext'] = _encode($ext);
      $tags = $this->m->n('tags');
      if(!empty($tags)) {
        $this->m->update($tags['uuid']);
      } else {
        $_POST['name'] = 'tags';
        $_POST['type'] = 'tag';
        $_POST['uuid'] =uniqid();
        $_POST['create_date'] = $_POST['update_date'] = time();
        $this->m->add();
      }
      redirect("?/admin/tag/");
    }

    $tags = $this->m->n('tags');
    $param['ext'] = _decode($tags['ext']);

    $this->display('v/admin/tag',$param);
  }

  function display($view='v/index',$param = array()){
    global $site;

    $param['site'] = $site;
    $param['menu'] =  array(
      'page'=>'页面',
      'link'=>'链接',
      'tag'=>'标签',
      'template'=>'模板',
      'layout'=>'排板',
      'model'=>'模型',
      'link'=>'链接',
      'tag'=>'标签',
       'profile'=>'账号',
      // 'site'=>'空间',
      'logout'=>'退出',
    );
    $param['al_content'] = view($view,$param,TRUE);
    header("Content-type: text/html; charset=utf-8");
    view('v/admin/template',$param);
  }

  function delimage($id,$model,$sid){
    $con = load("m/node_m")->get(" and `id`= '$id' and `sid` = '$sid'");
    $con['0']['meta'] = _decode($con['0']['meta']);
    $con['0']['meta'][$model] = "";
    $con['0']['meta'] = _encode($con['0']['meta']);
    load("m/node_m")->update($id,$con['0']);
  }

  function change_order(){

    $id = $_POST['uuid'];
    $elem['order'] = $_POST['order'];
    $this->m->update($id,$elem);
  }
}
